package weaver.interfaces.cese.duss.Test;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.cese.duss.ceseutil.OcrUitl;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-04-30
 * @Description: ${description}
 * @ModifyLog:
 **/

public class OCRTest {
    public static String httpPost(String path) {
        String result = "";
        try {
            File file = new File( path );
            URL url = new URL( "https://api.inspuronline.com/ai/ocr/v1/receipt/multiple" );
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            con.setDoOutput( true );
            con.setDoInput( true );
            con.setRequestMethod( "POST" );
            con.setUseCaches( false );
            con.setRequestProperty( "MediaType", "application/octet-stream" );
            con.setRequestProperty( "Content-Type", "application/octet-stream" );
            con.setRequestProperty( "X-API-Key", "52f19a5e-622f-ed63-1a23-2e0407ee1e2b" );
            OutputStream out = con.getOutputStream();
            //传入参数
            FileInputStream inputStream = new FileInputStream( file );
            byte[] data = new byte[2048];
            int len = 0;
            while ((len = inputStream.read( data )) != -1) {//将读取到的本地文件流读取到HttpsURLConnection,进行上传
                out.write( data, 0, len );
            }
            out.flush();
            inputStream.close();
            out.close();
            int code = con.getResponseCode(); //获取post请求返回状态
            System.out.println( "------------ORC接口返回CODE=" + code );
            BufferedReader br = new BufferedReader( new InputStreamReader( con.getInputStream(), "UTF-8" ) );
            result = br.readLine();
            //获取请求的资源
            con.disconnect();//断开HttpsURLConnection连接
            System.out.println("result="+result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        int userid = 1;//人员
        String department = "";//部门
        String supsubcom = "";//分部
        String currentDate = DateUtil.getCurrentDate();//当前日期
        String formmodeid = "";
        String msg = "";//返回信息
        boolean flag = true;//返回真假
        String result = httpPost( "D:\\download\\fplx\\400.jpg" );
        JSONObject resultJson = JSONObject.parseObject( result );
        //发票识别
        if (!"".equals( result )) {
            JSONObject response1 = JSONObject.parseObject( resultJson.getString( "response" ) );
            JSONObject data = JSONObject.parseObject( response1.getString( "data" ) );
            JSONArray identifyResults = JSONArray.parseArray( data.getString( "identifyResults" ) );
            for (int i = 0; i < identifyResults.size(); i++) {
                JSONObject results = (JSONObject) identifyResults.get( i );
                String category = results.getString( "category" );//发票类型
                JSONObject details = JSONObject.parseObject( results.getString( "details" ) );//发票识别的具体信息
                int fileId = 1;
                System.out.println( "=================category=" + category );
                switch (category) {
                    case "vat":
                        Map<String, Object> vatMap = getTicketType_var( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) vatMap.get( "flag" );
                        msg = (String) vatMap.get( "msg" );
                        break;
                    case "vat_roll":
                        Map<String, Object> vat_rollMap = getTicketType_var( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) vat_rollMap.get( "flag" );
                        msg = (String) vat_rollMap.get( "msg" );
                        break;
                    case "machine_invoice":
                        Map<String, Object> machine_invoiceMap = getTicketType_machine_invoice( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) machine_invoiceMap.get( "flag" );
                        msg = (String) machine_invoiceMap.get( "msg" );
                        break;
                    case "vehicle_invoice":
                        Map<String, Object> vehicle_invoiceMap = getTicketType_vehicle_invoice( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) vehicle_invoiceMap.get( "flag" );
                        msg = (String) vehicle_invoiceMap.get( "msg" );
                        break;
                    case "air_ticket":
                        Map<String, Object> air_ticketMap = getTicketType_air_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) air_ticketMap.get( "flag" );
                        msg = (String) air_ticketMap.get( "msg" );
                        break;
                    case "taxi_ticket":
                        Map<String, Object> taxi_ticketMap = getTicketType_taxi_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) taxi_ticketMap.get( "flag" );
                        msg = (String) taxi_ticketMap.get( "msg" );
                        break;
                    case "train_ticket":
                        Map<String, Object> train_ticketMap = getTicketType_train_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) train_ticketMap.get( "flag" );
                        msg = (String) train_ticketMap.get( "msg" );
                        break;
                    case "pass_ticket":
                        Map<String, Object> pass_ticketMap = getTicketType_pass_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) pass_ticketMap.get( "flag" );
                        msg = (String) pass_ticketMap.get( "msg" );
                        break;
                    case "bus_ticket":
                        Map<String, Object> bus_ticketMap = getTicketType_bus_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) bus_ticketMap.get( "flag" );
                        msg = (String) bus_ticketMap.get( "msg" );
                        break;
                    case "small_ticket":
                        Map<String, Object> small_ticketMap = getTicketType_small_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) small_ticketMap.get( "flag" );
                        msg = (String) small_ticketMap.get( "msg" );
                        break;
                    case "quota_invoice":
                        Map<String, Object> quota_invoiceMap = getTicketType_quota_invoice( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                        flag = (boolean) quota_invoiceMap.get( "flag" );
                        msg = (String) quota_invoiceMap.get( "msg" );
                        break;
                    default:
                        flag = false;
                        msg = "存在部分未识别的发票";
                }
            }
        } else {
            flag = false;
            msg = "影像识别接口异常,请联系管理员";
        }
        System.out.println( "flag=" + flag );
        System.out.println( "msg=" + msg );
    }

    //增值税电子普通发票/卷票
    public static Map<String, Object> getTicketType_var(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {
        System.out.println( "---------发票类型[var]" );
        System.out.println("--------details="+details.toJSONString());
        boolean flag = true;
        String msg = "";
        Map<String, Object> map = new HashMap<>();
        String invoiceType = "";
        invoiceType = OcrUitl.getOrcTicketType( category, details.getString( "invoiceType" ) );
        String logId = details.getString( "logId" );
        String invoiceCode = details.getString( "invoiceCode" );//发票代码
        String invoiceNum = details.getString( "invoiceNum" );//发票号码
        String invoiceDate = OcrUitl.transInvoiceDate( details.getString( "invoiceDate" ) );
        String totalAmount = details.getString( "totalAmount" );
        String sellerName = details.getString( "sellerName" );
        String checkCode = details.getString( "checkCode" );
        String sellerRegisterNum = details.getString( "purchaserRegisterNum" );
        JSONArray commodities = JSONArray.parseArray( details.getString( "commodities" ) );
        for (int j = 0; j < commodities.size(); j++) {
            Map<String,String> datMap = new HashMap<>(  );
            JSONObject jsonObject = (JSONObject) commodities.get( j );
            datMap.put("name",Util.null2String( jsonObject.getString( "name" )));//名称
            datMap.put("type",Util.null2String( jsonObject.getString( "type" )));//类型
            datMap.put("unit",Util.null2String( jsonObject.getString( "unit" )));//单位
            datMap.put("num",Util.null2String( jsonObject.getString( "num" )));//数量
            datMap.put("price",Util.null2String( jsonObject.getString( "price")));//价格
            datMap.put("amount",Util.null2String( jsonObject.getString( "amount" )));//总额

            String taxRate = Util.null2String( jsonObject.getString( "taxRate" ));//税率
            String newtaxRate = "".equals( taxRate ) ? "0" : OcrUitl.isNumberType(taxRate);//税率
            double newsl = Util.getDoubleValue( newtaxRate.replace( "%", "" ) ) / 100;
            datMap.put("taxRate",newsl+"");//税率
            datMap.put("tax",Util.null2String( jsonObject.getString( "tax" )));//税额
            System.out.println("发票明细:"+datMap.toString());
        }
        Map<String, Object> resultMap = YZTest.invoicerecertify( invoiceType, invoiceCode, invoiceNum, invoiceDate, totalAmount, checkCode, sellerRegisterNum );
        map.put( "flag", resultMap.get("flag") );
        map.put( "msg", resultMap.get( "msg" ) );
        return map;
    }

    //机打发票
    public static Map<String, Object> getTicketType_machine_invoice(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {
        RecordSet rs = new RecordSet();
        rs.writeLog( "---------发票类型[machine_invoice]" );
        boolean flag = true;
        String msg = "";
        Map<String, Object> map = new HashMap<>();
        String oaFplx = OcrUitl.getOrcTicketType( category, "" );
        String logId = details.getString( "logId" );
        String commodityName = details.getString( "commodityName" );
        String invoiceCode = details.getString( "invoiceCode" );
        String invoiceDate = OcrUitl.transInvoiceDate( details.getString( "invoiceDate" ) );
        String invoiceNum = details.getString( "invoiceNum" );
        String totalTax = details.getString( "totalTax" );
        map.put( "flag", flag );
        map.put( "msg", msg );
        return map;
    }

    ///机动车销售统一发票
    public static Map<String, Object> getTicketType_vehicle_invoice(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {
        RecordSet rs = new RecordSet();
        rs.writeLog( "---------发票类型[vehicle_invoice]" );
        boolean flag = true;
        String msg = "";
        String oaFplx = OcrUitl.getOrcTicketType( category, "" );
        String invoiceType = OcrUitl.getYZTicketType( oaFplx );
        Map<String, Object> map = new HashMap<>();
        String logId = details.getString( "logId" );
        String invoiceCode = details.getString( "invoiceCode" );
        String invoiceNum = details.getString( "invoiceNum" );
        String invoiceDate = OcrUitl.transInvoiceDate( details.getString( "invoiceDate" ) );
        String saler = details.getString( "saler" );
        String taxRate = details.getString( "taxRate" );
        String tax = details.getString( "tax" );
        String price = details.getString( "price" );
        Map<String, Object> resultMap = YZTest.invoicerecertify( invoiceType, invoiceCode, invoiceNum, invoiceDate, saler, "", "" );
        map.put( "flag", resultMap.get("flag") );
        map.put( "msg", resultMap.get( "msg" ) );
        return map;
    }

    //航空运输电子客票行程单
    public static Map<String, Object> getTicketType_air_ticket(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {
        // RecordSet rs = new RecordSet();
        System.out.println( "---------发票类型[air_ticket]" );
        boolean flag = true;
        String msg = "";
        String oaFplx = OcrUitl.getOrcTicketType( category, "" );
        Map<String, Object> map = new HashMap<>();
        String logId = details.getString( "logId" );
        String date = OcrUitl.transInvoiceDate( details.getString( "date" ) );
        String ticketRates = details.getString( "ticketRates" );
        String ticketNumber = details.getString( "ticketNumber" );
        double se = Double.valueOf( ticketRates ) / 1.09 * 0.09;//税额
        String sl = "0.09";//税率
        double bhsje = Double.valueOf( ticketRates ) - se;//不含税金额
        map.put( "flag", flag );
        map.put( "msg", msg );
        return map;
    }

    //出租车票
    public static Map<String, Object> getTicketType_taxi_ticket(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {
        RecordSet rs = new RecordSet();
        rs.writeLog( "---------发票类型[taxi_ticket]" );
        boolean flag = true;
        String msg = "";
        String oaFplx = OcrUitl.getOrcTicketType( category, "" );
        Map<String, Object> map = new HashMap<>();
        String logId = details.getString( "logId" );
        String date = OcrUitl.transInvoiceDate( details.getString( "date" ) );
        String invoiceCode = details.getString( "invoiceCode" );
        String fare = details.getString( "fare" );
        String invoiceNum = details.getString( "invoiceNum" );
        map.put( "flag", flag );
        map.put( "msg", msg );
        return map;
    }

    //火车票
    public static Map<String, Object> getTicketType_train_ticket(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {
       // RecordSet rs = new RecordSet();
       // rs.writeLog( "---------发票类型[train_ticket]" );
        boolean flag = true;
        String msg = "";
        String oaFplx = OcrUitl.getOrcTicketType( category, "" );
        Map<String, Object> map = new HashMap<>();
        String logId = details.getString( "logId" );
        String date = OcrUitl.transInvoiceDate( details.getString( "date" ) );
        String ticketNum = details.getString( "ticketNum" );
        String serialNumber = Util.null2String( details.getString( "serialNumber" ) );
        String ticketRates = details.getString( "ticketRates" );
        double se = Double.valueOf( ticketRates ) / 1.09 * 0.09;//税额
        String sl = "0.09";//税率
        double bhsje = Double.valueOf( ticketRates ) - se;//不含税金额
        System.out.println("serialNumber="+serialNumber);
        map.put( "flag", flag );
        map.put( "msg", msg );
        return map;
    }

    //过路费发票
    public static Map<String, Object> getTicketType_pass_ticket(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {
        RecordSet rs = new RecordSet();
        rs.writeLog( "---------发票类型[pass_ticket]" );
        boolean flag = true;
        String msg = "";
        String oaFplx = OcrUitl.getOrcTicketType( category, "" );
        Map<String, Object> map = new HashMap<>();
        String logId = details.getString( "logId" );
        String code = details.getString( "code" );
        String number = details.getString( "number" );
        String date = OcrUitl.transInvoiceDate( details.getString( "date" ) );
        String total = details.getString( "total" );

        map.put( "flag", flag );
        map.put( "msg", msg );
        return map;
    }

    //客运汽车（含船票）
    public static Map<String, Object> getTicketType_bus_ticket(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {
        RecordSet rs = new RecordSet();
        rs.writeLog( "---------发票类型[bus_ticket]" );
        boolean flag = true;
        String msg = "";
        String oaFplx = OcrUitl.getOrcTicketType( category, "" );
        Map<String, Object> map = new HashMap<>();
        String logId = details.getString( "logId" );
        String code = details.getString( "code" );
        String number = details.getString( "number" );
        String date = OcrUitl.transInvoiceDate( details.getString( "date" ) );
        String total = details.getString( "total" );
        double se = Double.valueOf( total ) / 1.09 * 0.03;//税额
        String sl = "0.03";//税率
        double bhsje = Double.valueOf( total ) - se;//不含税金额

        map.put( "flag", flag );
        map.put( "msg", msg );
        return map;
    }

    //国际小票
    public static Map<String, Object> getTicketType_small_ticket(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {
        RecordSet rs = new RecordSet();
        rs.writeLog( "---------发票类型[small_ticket]" );
        boolean flag = true;
        String msg = "";
        String oaFplx = OcrUitl.getOrcTicketType( category, "" );
        Map<String, Object> map = new HashMap<>();
        String logId = details.getString( "logId" );
        String date = OcrUitl.transInvoiceDate( details.getString( "date" ) );
        String total = details.getString( "total" );
        String tax = details.getString( "tax" );
        double bhsje = Double.valueOf( total ) - Double.valueOf( tax );
        String sql = "insert into uf_fpxx(fplrr,lrrq,ssfgs,ssfrzz,fpdm,fphm,fprq,fplx,je,bhsje,se,sl,xfdwmc,fpzt,fpyx,fpzw,formmodeid,logid) " +
                "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        rs.executeUpdate( sql, new Object[]{userid, currentDate, supsubcom, department, logId, "", date, oaFplx, total, bhsje, tax, "", "", "", "0", fileId, "2", formmodeid, logId} );
        map.put( "flag", flag );
        map.put( "msg", msg );
        return map;
    }
    //定额发票
    public static Map<String, Object> getTicketType_quota_invoice(int userid, String currentDate, String supsubcom, String department, int fileId, String formmodeid, String category, JSONObject details) {

        System.out.println( "---------发票类型[quota_invoice]" );
        boolean flag = true;
        String msg = "";
        String oaFplx = OcrUitl.getOrcTicketType( category, "" );
        Map<String, Object> map = new HashMap<>();
        String logId = details.getString( "logId" );
        String invoiceCode = details.getString( "invoiceCode" );
        String invoiceNumber = details.getString( "invoiceNumber" );
        String invoiceRate = details.getString( "invoiceRate" );
        map.put( "flag", flag );
        map.put( "msg", msg );
        return map;
    }

}